/**
 * 登录模块
 */
var Login = function () {
    //变量赋值
    var $account = $('#account');
    var $password = $('#password');
    var $captcha = $('#captcha');
    var $captchaImg = $('#captcha_img');
    var $autoLogin = $('#auto_login');
    var $form = $('#login_form');
    var $btnLogin = $('#btn_login');
    var $captchaContainer = $('.captcha-container');
    var loginUrl = $form.data('url');
    var lockUrl = $form.data('lockUrl');
    var uuid = jx.uuid();

    // var timeoutHandle = -1;

    /**
     * 初始化验证码
     */
    var initCaptcha = function () {
        refreshCaptcha();
        $captchaImg.on('click', refreshCaptcha);
    };

    /**
     * 刷新验证码
     */
    var refreshCaptcha = function () {
        var url = $captchaImg.data('url') + '?uuid=' + uuid + '&_t=' + Math.random();
        $captchaImg.attr('src', url);
    };

    /**
     * 显示消息
     * @param msg 消息内容
     */
    var showMsg = function (msg) {
        toastr.options.timeOut = 8000;
        toastr.options.progressBar = true;
        toastr.options.positionClass = 'toast-top-center';
        toastr.remove();
        toastr.error(msg);
    };

    /**
     * 隐藏消息
     */
    var hideMsg = function () {
        toastr.remove();
    };

    /**
     * 获取随机数字
     * @param {number} max 随机数最大值
     * @returns {number} 返回从1到最大值的随机数
     */
    var getRandomNumber = function (max) {
        return Math.floor(Math.random() * max + 1);
    };

    /**
     * 设置页面背景图片
     */
    var setBackground = function () {
        if (jx.autoBackground === true) {
            var num = getRandomNumber(jx.autoBackgroundSize || 24);
            setBackgroundCore(num);
        }
        else if (jx.defaultBackground) {
            setBackgroundCore(jx.defaultBackground || 1);
        }
    };

    /**
     * 设置页面背景图片
     */
    var setBackgroundCore = function (num) {
        var path = jx.formatString('{0}auth/img/bg/bg{1}.jpg', jx.rootPath, num);
        $('body').css('background', 'url(' + path + ')');
    };


    /**
     * 初始化控件事件
     */
    var initEvent = function () {

        $btnLogin.on('click', function () {
            hideMsg();
            checkLock();
        });

        $account.on('keydown', function (e) {
            hideMsg();
            if (e.keyCode === 13) { //回车
                if (!$(this).val().length) {
                    showMsg($(this).data('msg'));
                }
                else {
                    $password.focus();
                }
            }
        });

        $password.on('keydown', function (e) {
            hideMsg();
            if (e.keyCode === 27) { //Esc
                $account.focus();
                return;
            }
            if (e.keyCode === 13) { //回车
                if (!$(this).val()) {
                    showMsg($(this).data('msg'));
                }
                else {
                    checkLock();
                }
            }
        });

        $captcha.on('keydown', function (e) {
            hideMsg();
            if (e.keyCode === 13) { //回车
                if (!$(this).val()) {
                    showMsg($(this).data('msg'));
                }
                else {
                    jx.closeAllDialog();
                    login();
                }
            }
        });
    };

    /**
     * 验证文本框
     * 验证通过返回true,不通过返回false
     */
    var valid = function () {
        if (!$account.val()) {
            showMsg($account.data('msg'));
            $account.focus();
            return false;
        }
        if (!$password.val()) {
            showMsg($password.data('msg'));
            $password.focus();
            return false;
        }
        if ($password.val().length > 30) {
            showMsg('密码长度不能超过30位');
            $password.focus();
            return false;
        }

        if (!loginUrl) {
            showMsg('请指定登录验证Url');
            return false;
        }
        return true;
    };

    /**
     * 禁用文本框
     */
    var disableInput = function () {
        // timeoutHandle = setTimeout(function () {}, 500);
        $account.attr('disabled', '');
        $password.attr('disabled', '');
        $autoLogin.attr('disabled', '');
        $btnLogin.val('登录中..').attr('disabled', '');
    };

    /**
     * 启用文本框
     */
    var enableInput = function () {
        // clearTimeout(timeoutHandle);
        $account.removeAttr('disabled');
        $password.removeAttr('disabled');
        $autoLogin.removeAttr('disabled');
        $btnLogin.val('登 录').removeAttr('disabled');
    };

    /**
     * 获取提交的数据
     */
    var getPostData = function () {
        //var pubkey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaa9HnhyNTF1O8ChMmPPKZC8NFSCw+didy6Rf/nTBdzF/y/wvgz9CVfDjmatetmj3zLaFiyWjHCYw6f7e+TKGKCSq92qVGIFkCIhWoMcPPigrV8x75OjzZnfvfJsoOyllh7GqCJYAVLBq37wyWjOEXmJ41yHUv10e+562YP000KQIDAQAB';
        //// 利用公钥加密
        //var encrypt = new JSEncrypt();
        //encrypt.setPublicKey(pubkey);

        var d = {
            account: $account.val(),
            //password: encrypt.encrypt($password.val()),
            password: $password.val(),
            captcha: $captcha.val(),
            uuid: uuid,
            autoLogin: $autoLogin.prop('checked')
        };
        return d;
    };

    /**
     * 检查锁定信息
     */
    var checkLock = function () {
        if (!valid()) {
            return;
        }
        hideMsg();

        $.ajax({
            url: lockUrl,
            type: 'post',
            // dataType: 'json',
            data: {account: $account.val()}
        }).done(function (result) {

            if (result.success) {
                //需要验证码
                jx.dialog({
                    title: '验证码',
                    content: $('#captcha-container'),
                    width: '400px',
                    height: '120px',
                    closeBtn: 0,
                    //btn: '登录',
                    success: function (layero, index) {
                        refreshCaptcha();
                        $captcha.val('');
                        $captcha.focus();
                    },
                    //yes: function (index, layero) {
                    //    if (!$captcha.val()) {
                    //        showMsg($captcha.data('msg'));
                    //    }
                    //    else {
                    //        jx.closeAllDialog();
                    //        login();
                    //    }
                    //}
                });

            } else {
                //不需要验证码,直接提交
                login();
            }
        }).fail(function (request) {
            if (request.responseJSON) {
                showMsg(request.responseJSON.message || '检查锁定信息失败');
            }
            else {
                showMsg(request.statusText || '检查锁定信息失败');
            }
        });
    };

    /**
     * 系统登录
     */
    var login = function () {
        hideMsg();
        disableInput();
        var send = function () {
            $.ajax({
                url: loginUrl,
                type: 'post',
                // dataType: 'json',
                data: getPostData()
            }).done(function (result) {
                if (result.success) {
                    $btnLogin.val('登陆成功,正在跳转...');
                    var hash = window.location.hash;
                    window.location.href = result.data.url + hash || jx.apiUrl("/") + hash;
                } else {
                    if (result.msg) {
                        showMsg(result.msg);
                    }
                    enableInput();
                    refreshCaptcha();
                    $captcha.val('');
                    $password.focus();
                }
            }).fail(function (request) {
                if (request.responseJSON) {
                    showMsg(request.responseJSON.message || '登录失败');
                }
                else {
                    showMsg(request.statusText || '登录失败');
                }
                enableInput();
            });
        };
        send();
        //jx.require('encrypt', send);
    };

    /**
     * 系统登录初始化
     */
    var init = function () {
        setBackground();
        initCaptcha();
        initEvent();
        if (self != top) {
            top.location.href = jx.apiUrl("/");
        }
    }();
};

jx.ready(function () {
    jx.defaultBackground = 24;  //默认背景图片序号
    jx.autoBackground = true;  //是否启用自动切换背景
    jx.autoBackgroundSize = 5; //自动切换背景图片数量
    window.login = Login();
});